package cn.zju.controllers;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.ansj.splitWord.analysis.ToAnalysis;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.zju.Service.ISearchEngineService;
import cn.zju.pojo.Pages;
import cn.zju.pojo.Relate;

@Controller
@RequestMapping(value = "/SearchEngine")
public class SearchEngineController {

	@Resource
	private ISearchEngineService searchEnginService;

	// 进入首页
	@RequestMapping(value = "/index", method = { RequestMethod.GET })
	public String index(HttpServletRequest request, Model model) {
		return "index";
	}

	// 点击输入之后
	@RequestMapping(value = "/search", method = { RequestMethod.POST })
	public String search(HttpServletRequest request, Model model) {
		String search = request.getParameter("search");
		model.addAttribute("search", search);
		List<Pages> pages = null;
		List<Relate> relate = null;
		// 去除空格
		search = search.replace(" ", "");
		// 中文分词
		String a = ToAnalysis.parse(search).toString();
		String deal = a.substring(1, a.length() - 1);
		String after[] = deal.split(",");

		if (after.length > 1) {
			pages = searchEnginService.selectByKeyWordB((after[0].trim().split("/"))[0],
					(after[1].trim().split("/"))[0]);
			relate = searchEnginService.selectRelateByKeyWordB((after[0].trim().split("/"))[0],
					(after[1].trim().split("/"))[0]);
		} else {
			// 单个参数查询
			pages = searchEnginService.selectByKeyWordA(search);
			relate = searchEnginService.selectRelateByKeyWordA(search);

		}
		// 返回查询列表
		model.addAttribute("pages", pages);
		model.addAttribute("relate", relate);
		return "search";
	}
}
